from nicegui import ui, app
from orm import manager

class MessageSend():
    def send_message(self):
        text = self.text.value
        if app.storage.general.get("messages", "none") == "none":
            app.storage.general["messages"] = {}
        user = manager.get_user(app.storage.user["username"])
        toid = self.to.id
        if not(toid in app.storage.general["messages"]):
            app.storage.general["messages"][toid]=[]
        app.storage.general["messages"][toid].append({"from": user.username, "content":text})
        self.dialog.close()
    def __init__(self, targetuser):
        self.to = targetuser
        with ui.dialog() as self.dialog, ui.card().tight().classes('w-[800px] h-[600px]'):
            with ui.column().classes("w-full h-full"):
                self.text = ui.textarea("输入信息").classes("w-full h-4/5")
                ui.button("发送！",  color='text-indigo-700',on_click=lambda: self.send_message()).classes("w-full grow bg-gradient-to-br from-purple-200 to-blue-200")
        self.dialog.open()

class MessageReceive():
    def refresh(self):
        with self.card:
            self.card.clear()
            with ui.column().classes("w-full h-full"):
                for message in self.messages:
                    ui.chat_message(message["content"], name = message["from"]).classes('w-full ml-6 mt-3')
                if len(self.messages)>0:
                    ui.button("已读！", color='text-indigo-700', on_click=lambda :self.clear()).classes("w-full bg-gradient-to-r from-blue-100 to-purple-50")
    def clear(self):
        self.messages.clear()
        self.refresh()

    def __init__(self):
        user = manager.get_user(app.storage.user["username"])
        self.userid = user.id
        if (app.storage.general.get("messages", "none")!='none') and\
                (self.userid in app.storage.general["messages"]):
            self.messages = app.storage.general["messages"][self.userid]
        else:
            self.messages=[]
        self.card = ui.card().tight().classes('w-full h-fit bg-gradient-to-br from-purple-200 to-blue-200')
        self.refresh()